package com.study.javaBasic.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * The type Proxy demo.
 *
 * @Name: 代理
 * @Description: java类作用描述
 * @Author: yn
 * @CreateDate: 2021 /12/22 15:39
 * @Remark: 特殊说明
 * @Version: 1.0
 */
public class ProxyDemo {
    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {
        staticProxy();
        System.out.println("---------------");
        ISendMsg o = (ISendMsg) dynamicProxy(SMS.class);
        o.send("你好");
        System.out.println("---------------");
        ISendMsg cgProxy = (ISendMsg) dynamicCGProxy(SMS.class);
        cgProxy.send("你好");
    }

    /**
     * 静态代理方法测试
     */
    public static void staticProxy() {
        SendMsgProxy proxy = new SendMsgProxy(new SMS());
        proxy.send("你好");
    }

    /**
     * 动态代理方法测试
     *
     * @param cls 被代理对象
     */
    public static Object dynamicProxy(Class cls) {
        return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), (Object proxy, Method method, Object[] args) -> {
            System.out.println("++++开始+++++");
            Object invoke = method.invoke(cls.newInstance(), args);
            System.out.println("++++结束+++++");
            return invoke;
        });
    }

    /**
     * 动态代理方法测试
     *
     * @param cls 被代理对象
     */
    public static Object dynamicCGProxy(Class cls) {
        // 创建动态代理增强类
        Enhancer enhancer = new Enhancer();
        // 设置类加载器
        enhancer.setClassLoader(cls.getClassLoader());
        // 设置被代理类
        enhancer.setSuperclass(cls);
        // 设置方法拦截器
        enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
            System.out.println("++++开始+++++");
            System.out.println(method);
            Object invoke = methodProxy.invoke(cls.newInstance(), objects);
            System.out.println("++++结束+++++");
            return invoke;
        });
        // 创建代理类
        return enhancer.create();
    }


}
